import { useStorage } from '@vueuse/core'
import { defineStore } from 'pinia'

import { commonApi } from '@/apis'
import type { GetPermissionRes } from '@/apis/commonTypes'

import { usePermissionStore, useTabsStore } from '.'

export function useUserStore() {
  return defineStore('user', {
    state: () => {
      return {
        token: useStorage('token', '') as unknown as string,
        tokenName: useStorage('tokenName', '') as unknown as string,
        name: useStorage('name', '') as unknown as string,
        userId: useStorage('userId', '') as unknown as string,
        roles: [] as string[]
      }
    },
    actions: {
      async login(payload: Record<string, any>) {
        const data = await commonApi.login(payload)
        this.token = data.tokenInfo.tokenValue
        this.tokenName = data.tokenInfo.tokenName
        this.name = data.userName
        this.userId = data.userId
      },
      async logout() {
        await commonApi.logout()
        this.clear()
      },
      async getPermissions() {
        const roles = await commonApi.getPermissions(this.userId)

        this.roles = this._flattenRoles(roles || [])

        return this.roles
      },
      /** 清除缓存 */
      clear() {
        const tabsStore = useTabsStore()
        const permissionStore = usePermissionStore()

        this.token = ''
        this.name = ''
        this.roles = []
        tabsStore.delAllTabs()
        permissionStore.delAllRoutes()
      },
      _flattenRoles(arr: GetPermissionRes, result: string[] = []) {
        for (const item of arr) {
          result.push(item.sourceName)

          if (Array.isArray(item.children)) {
            this._flattenRoles(item.children, result)
          }
        }
        return result
      }
    }
  })()
}
